<?php

namespace App\Admin\Controllers;

use App\Models\InventoryFunc;
use App\Models\OutTransferBillDetail;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Widgets\Form as myForm;


class TransferOutsController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('调拨出库管理');
            $content->description('');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('调拨出库管理');
            $content->description('');

            $content->body($this->editForm()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('调拨出库管理');
            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(OutTransferBillDetail::class, function (Grid $grid) {
            $grid->model()->select('out_transfer_bill_detail.*','out_transfer_bill_detail.id as detail_id','company.name',
                'sku.name as sku_name',
                //'warehouse.name as warehouse_name'
                'transfer_bill.*','admin_users.name as operater_name','out_warehouse.name as out_warehouse_name','in_warehouse.name as in_warehouse_name')
            ->leftjoin('transfer_bill','transfer_bill.id','=','out_transfer_bill_detail.transfer_bill_id')
            ->leftjoin('warehouse as out_warehouse','out_warehouse.id','=','transfer_bill.out_warehouse_id')
            ->leftjoin('warehouse as in_warehouse','in_warehouse.id','=','transfer_bill.in_warehouse_id')
            ->leftjoin('company','company.id','=','transfer_bill.company_id')
            ->leftjoin('admin_users','admin_users.username','=','transfer_bill.operater_id')
            ->leftjoin('sku','sku.id','=','out_transfer_bill_detail.sku_id')
            ->where('transfer_bill.company_id',Admin::user()->company_id)
            ->orderBy('transfer_bill.created_at', 'desc');
           $grid->transfer_bill_id('调拨单编号')->sortable();
            $grid->sku_name('SKU名称');
            $grid->name('所属公司');
            $grid->operater_name('调度员');
            $grid->send_time('出库时间');
            $grid->out_warehouse_name('调出仓库名称');
            $grid->in_warehouse_name('调入仓库名称');


            $grid->out_state('出库状态')->display(function($v){
                return HelpersController::getStateValue('transferBillState',$v);
            });
            $grid->review_out_state("出库审核状态")->display(function($v){
                return HelpersController::getStateValue('transferBillReviewState',$v);
            });

            $grid->disableCreateButton();//禁用新增按钮
            $grid->disableExport();//禁用导出按钮
            $grid->actions(function ($actions) {
                // append一个操作
                $actions->disableEdit();
                $actions->disableDelete();//禁用删除
                $actions->prepend('<a href="'.\Route('transferOuts.show',['id'=>$actions->row['detail_id']]).'"><i class="fa fa-eye"></i></a>');
            });

             $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                $filter->where(function ($query) {
                    $query->where('out_transfer_bill_detail.transfer_bill_id', 'like', "%{$this->input}%");
                }, '调拨单编号');

                $filter->where(function ($query) {
                    $query->where('sku.name', 'like', "%{$this->input}%");
                }, 'SKU名称');

                $filter->where(function ($query) {
                    $query->where('admin_users.name', 'like', "%{$this->input}%");
                }, '调度员 ');

                // $filter->where(function ($query) {

                //     $query->where('transfer_bill.operater_id',$this->input);

                // }, '销售员')->select(\DB::table('admin_users')->leftjoin('admin_role_users','admin_role_users.user_id','=','admin_users.id')->where('admin_role_users.role_id','4')->pluck(\DB::raw('admin_users.name'),\DB::raw('admin_users.username')));
            });
        });
    }

    public function show($id)
    {
        $model = new Content();

        $data = \DB::table('out_transfer_bill_detail')->select('admin_users.name as user_name','company.name as company_name'
            //,'warehouse.name as warehouse_name'
            ,'transfer_bill.*','out_transfer_bill_detail.*','out_warehouse.name as out_warehouse_name','in_warehouse.name as in_warehouse_name','sku.name as sku_name','batch_grade.name as batch_grade','batch_thick.name as batch_thick','batch_origin.name as batch_origin','batch_colour.name as batch_colour','batch_avg_size.name as batch_avg_size','batch_min_size.name as batch_min_size','reviewer.name as reviewer_name','inventory.inventory_id as bid','inventory.grade','inventory.origin','inventory.colour','inventory.over_size','inventory.over_num','inventory.thick','inventory.min_size','inventory.avg_size')
                        ->leftjoin('transfer_bill','transfer_bill.id','=','out_transfer_bill_detail.transfer_bill_id')
                        ->leftjoin('warehouse as out_warehouse','out_warehouse.id','=','transfer_bill.out_warehouse_id')
                        ->leftjoin('warehouse as in_warehouse','in_warehouse.id','=','transfer_bill.in_warehouse_id')
                        ->leftjoin('admin_users','admin_users.username','=','transfer_bill.operater_id')
                        // ->leftjoin('admin_users as documentary','documentary.username','=','agent.merchandiser')
                        // ->leftjoin('admin_users as salesman','salesman.username','=','agent.salesman')
                        ->leftjoin('admin_users as reviewer','reviewer.username','=','transfer_bill.reviewer_id')
                        ->leftjoin('company','company.id','=','transfer_bill.company_id')
                        //->leftjoin('warehouse','warehouse.warehouse_id','=','purchase.warehouse_id')
                        ->leftjoin('inventory','inventory.id','=','out_transfer_bill_detail.inventory_id')
                        ->leftjoin('sku','out_transfer_bill_detail.sku_id','=','sku.id')
                        ->leftjoin('batchattribute as batch_grade','inventory.grade','=','batch_grade.id')
                        ->leftjoin('batchattribute as batch_thick','inventory.thick','=','batch_thick.id')
                        ->leftjoin('batchattribute as batch_origin','inventory.origin','=','batch_origin.id')
                        ->leftjoin('batchattribute as  batch_colour','inventory.colour','=','batch_colour.id')
                        ->leftjoin('batchattribute as batch_avg_size','inventory.avg_size','=','batch_avg_size.id')
                        ->leftjoin('batchattribute as batch_min_size','inventory.min_size','=','batch_min_size.id')
                        ->where('out_transfer_bill_detail.id',$id)->first();

 $content = '<div style="width:80%;margin:0 auto;background:#fff;padding:10px;"><h4 style="text-align:center;">基本信息</h4><hr>';
        $headers = [];
        $rows = [
            ['调拨单编号', $data->transfer_bill_id, '物流方式', HelpersController::getStateValue('Logistics',$data->logistics)],
            ['调出仓库',$data->out_warehouse_name,'调入仓库',$data->in_warehouse_name],
            ['所属公司', $data->company_name, '出库时间',$data->send_time]
        ];
        $table_1 = new Table($headers, $rows);
        $content .= $table_1->render();


        $content .= '<h4 style="text-align:center;">系统信息</h4><hr>';

        // table 2
        $headers = [];
        $rows = [
            ['操作人',$data->user_name,'调拨单状态',  HelpersController::getStateValue("transferBillState",$data->transfer_bill_out_state)." | ".HelpersController::getStateValue("transferBillState",$data->transfer_bill_in_state)],
            ['最后操作人',$data->reviewer_name,'最后操作时间',$data->review_time],
            ['单据生成时间', $data->created_at,'',''],
        ];

        $table_2 = new Table($headers, $rows);
        $content .=  $table_2->render();

        $content .= '<h4 style="text-align:center;">批次信息</h4><hr>';

        // table 2
        $headers = [];
        $rows = [
            ['SKU编号',$data->sku_id,'SKU名称', $data->sku_name ],
            ['等级',$data->batch_grade?$data->batch_grade:"未维护",'厚度',$data->batch_thick?$data->batch_thick:"未维护" ],
            ['产地', $data->batch_origin?$data->batch_origin:"未维护",'颜色',$data->batch_colour?$data->batch_colour:"未维护"],
            ['平均尺寸', $data->batch_avg_size?$data->batch_avg_size:"未维护",'最小尺寸',$data->batch_min_size?$data->batch_min_size:"未维护"],
            ['出库状态', HelpersController::getStateValue('outState',$data->out_state),'批次ID',$data->inventory_id]

        ];
        $table_3 = new Table($headers, $rows);

        $content .=  $table_3->render();

        $content .= "<h4 style='text-align:center'>备注</h4><hr><p style='background:#efefef;padding:8px;'>".(trim($data->remark)?$data->remark:"无")."</p>";
        $content .= '<h4 style="text-align:center;">仓库设置</h4><hr>';
        $form = new myForm();
        $form->__construct(
            [
                'sku_id'=>$data->sku_id,
                'sku_name'=>$data->sku_name,
                'inventory_id'=>$data->bid,
                'out_state'=>$data->out_state,
                'bid'=>$data->bid
            ]);
        $form->action($data->id.'/finance');
        $form->method('POST');
        $form->disablePjax();
        $form->hidden('out_transfer_bill_detail_id')->default($data->id);
        $form->hidden('transfer_bill_id')->default($data->transfer_bill_id);
        $form->hidden('sku_id')->default($data->sku_id);
        $form->hidden('inventory_id')->default($data->bid);
        $form->hidden('inventory_sn')->default($data->inventory_id);

        $form->display('sku_name','sku');
        $form->display('bid','批次');
        $form->radio('out_state','出库状态')->options(["PART_OUT"=>'部分出库',"ALL_OUT"=>'全部出库']);
        $hadOut = \DB::table('inventory_checking_detail')->select(\DB::raw('sum(num) as num'),\DB::raw('sum(size) as size'))->where(['checking_ASN'=>$data->transfer_bill_id,'type'=>1,'sku_id'=>$data->sku_id])->first();
        $form->currency('arrive_num','实际出库张数')->symbol("")->help('单据数量： '.round($data->num,2).' ，库存可用张数: '.round($data->over_num,2).' ，已出库张数: '.round($hadOut->num,2));
        $form->currency('arrive_size','实际出库尺数')->symbol("")->help('单据数量： '.round($data->size,2).' ，库存可用尺数: '.round($data->over_size,2).' ，已入库尺数: '.round($hadOut->size,2));
        // $form->html('<button type="button" class="btn">选择批次</button>','');


        if($data->review_out_state == "CHARGE_OUT_CHECK"){
            if($data->out_state == "ALL_OUT"){
                $content.='<p style="text-align:center"> 已全部出库</p>';
            }else{
                $content .= $form->render();
            }

        }elseif($data->review_out_state == "OUT_CHECK"){
            $content.='<p style="text-align:center"> 单据已完成出库</p>';
        }else{
            $content.='<p style="text-align:center"> 需要等待主管审核通过后操作</p>';
        }

        $items = [
            'header'      => '调拨出库处理',
            'description' => 'TransferOut',
            'breadcrumb'  => '',
            'content'     => $content."</div>",
        ];

        return view('admin::content', $items)->render();
    }

    public function finance($id){
        $input = \Illuminate\Support\Facades\Input::all();
        $old = \DB::table('transfer_bill')->where('id',$input['transfer_bill_id'])->first();
        // if($old->transfer_bill_out_state == 3 ){
        //     admin_toastr("订单已全部出库,如要变更请联系系统管理员");
        //     return back()->withInput();
        // }
        if($old->transfer_bill_out_state == "ALL_OUT" ){
            admin_toastr("该SKU已全部出库,如要变更请联系系统管理员",'error');
            return back()->withInput();
        }
        if(!isset($input['out_state'])){
            admin_toastr("出库状态必填","error");
            return back()->withInput();
        }
        if($input['arrive_num']<=0){
            admin_toastr("出库张数至少大于0","error");
            return back()->withInput();
        }

        if($input['arrive_size']<=0){
            admin_toastr("出库尺寸至少大于0","error");
            return back()->withInput();
        }
        if(!$input['inventory_sn']){
            admin_toastr("出库批次必须选择","error");
            return back()->withInput();
        }
        if(!$input['inventory_id']){
            admin_toastr("系统错误，刷新后重试","error");
            return back()->withInput();
        }

            // 出库锁定尺寸
                // $hadOut = \DB::table('inventory_checking_detail')->select(\DB::raw('sum(num) as num'),\DB::raw('sum(size) as size'))->where(['checking_ASN'=>$input['transfer_bill_id'],'type'=>3,'sku_id'=>$input['sku_id']])->first();
                $inventory = \DB::table('inventory')->where(['id'=>$input['inventory_sn'],'sku_id'=>$input['sku_id']])->first();

                $inventoryNumCnt = $inventory->over_num;
                $inventorySizeCnt = $inventory->over_size;
                if( $input['arrive_num'] > $inventoryNumCnt){
                    admin_toastr("该批次没有那么多数量张数的库存","error");
                    return back()->withInput();
                }
                if( $input['arrive_size'] > $inventorySizeCnt){
                    admin_toastr("该批次没有那么多数量尺寸的库存","error");
                    return back()->withInput();
                }

        // $olddetail = \DB::table('out_transfer_bill_detail')->leftjoin('inventory','inventory.id','=','out_transfer_bill_detail.inventory_id')->where('out_transfer_bill_detail.id',$id)->first(); // 可以与下方sql优化成一条


        // $validator = \Validator::make($input, [
        //     'transfer_bill_out_state' => 'required',
        //     'arrive_num'=>'required',
        //     // 'warehouse_id'=>'required',
        //     // 'warehouse_zone_id'=>'required',
        //     // 'warehouse_location_id '=>'required',
        //     'inventory_id' => 'required'
        // ]);
        // if ($validator->fails()) {
        //     return back()->withInput()->withErrors($validator->errors());
        // }
        $old_details = \DB::table('out_transfer_bill_detail')->where([['id','<>',$id],['transfer_bill_id',$input['transfer_bill_id']]])->get();
        if(count($old_details) > 0){
            if($input['out_state'] == "PART_OUT"){
                $operate_state = "PART_OUT";
            }else{
                $operate_state = "ALL_OUT";
                foreach ($old_details as $old_detail) {
                    if($old_detail->out_state != "ALL_OUT"){
                        $operate_state = "PART_OUT";
                        break;
                    }
                }
            }

        }else{
            $operate_state = $input['out_state'];
        }
        $update_transfer_bill_datas['transfer_bill_out_state'] = $operate_state;
        if($operate_state == "ALL_OUT"){
            $update_transfer_bill_datas['review_out_state'] = "OUT_CHECK";
        }
        $model = new InventoryFunc("out_transfer",$id);
        try{
            \DB::beginTransaction();
            $model->insertTransferInventoryAndCheckingOne($input);
            \DB::table('transfer_bill')->where(['id'=>$input['transfer_bill_id']])->update($update_transfer_bill_datas);
            \DB::table('out_transfer_bill_detail')->where(['id'=>$id])->update(['out_state'=>$input['out_state']]);

            /** 生成 调拨在途 （暂时在生成单据时候一并生成） 详细查看 TransBillController[store]
            $arrs =[
                        'sku_id'=>$input['sku_id'],
                        'type'=>6,
                        'num'=>$input['arrive_num'],
                        'size'=>$input['arrive_size'],
                        'operater_id'=>Admin::user()->username,
                        'checking_ASN'=>$input['transfer_bill_id'],
                        'inventory_id'=>$input['inventory_id'],
                        'grade'=>$inventory->grade,
                        'thick'=>$inventory->thick,
                        'origin'=>$inventory->origin,
                        'colour'=>$inventory->colour,
                        'avg_size'=>$inventory->avg_size,
                        'min_size'=>$inventory->min_size,
                        'created_at'=>date('Y-m-d H:i:s')
                    ];
            \DB::table('inventory_checking_detail')->insert($arrs);
            */
            \DB::commit();

            admin_toastr("出库成功");
            $url = route('transferOuts.index');
            return redirect($url);
        }catch (Exception $e) {
            \DB::rollBack();
            admin_toastr("数据库出错，请联系管理员","error");
            return back()->withInput();

        }
    }
}
